<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2020/6/24
 * Time: 9:44
 */

namespace App\Services;


use App\Models\Coupon;
use App\Models\ServiceType;
use App\Models\UserCoupon;

class CouponService extends BaseService
{
    protected $coupon;

    public function __construct()
    {
        $this->coupon = new Coupon();
    }

    /**
     * 优惠券列表
     */
    public function get_list(string $name)
    {
        $list = $this->coupon->with('service_type:id,coupon_id,service_type_id')
            ->select(['id', 'name', 'rules', 'type', 'coupon_value', 'use_full'])
            ->where('name', $name)
            ->orWhere('name', 'like', '%' . $name . '%')
            ->where('status', 1)
            ->get();
        return $this->sss($list);
    }

    /**
     * @param $list
     * @return mixed
     */
    public function sss($list)
    {
        if (!$list) return $list;

        foreach ($list as &$item) {
            if ($item['service_type']) {
                $arr = [];
                foreach ($item['service_type'] as $key => $value) {
                    $arr[] = ServiceType::query()->select('name')->where('id', $value['service_type_id'])->first();
                }
            }
            $item['service'] = $this->names($arr);
            unset($item['service_type']);
        }
        return $list;
    }

    public function names(array $ProTopicid)
    {
        $string = '';
        foreach ($ProTopicid as $valueId) {
            $string .= rtrim($valueId['name'] . ',');

        }
        $string = rtrim($string, ',');
        return $string;
    }

    /**
     * 发放用户活动奖励
     * @param $user_id
     * @param $activity_id
     * @param int $company_id
     * @return bool
     */
    public function grantActivityCoupon(int $user_id, int $coupon_id)
    {
        $user_coupon_info = Coupon::query()->where('id', $coupon_id)->first(['id', 'validity_day']);
        $insert_data = [
            'user_id' => $user_id,
            'company_id' => 1,
            'activity_id' => 0,
            'coupon_id' => $coupon_id,
            'from' => 2, //来源 1-领取 2-系统发放
            'status' => 1,
            'receive_time' => time(),
            'overdue_time' => $user_coupon_info->validity_day ? time() + $user_coupon_info->validity_day * 86400 : 0
        ];
        return UserCoupon::query()->create($insert_data);
    }
}